package com.futao.springbootlearn20220224.redis.scan;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author futao@gmail.com
 * @date 2022/4/14
 */
@Slf4j
@RequestMapping("/redis/scan")
@RestController
public class HashScanDemo {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/hash")
    public void hashScan() throws InterruptedException {
        stringRedisTemplate.delete("scan:hash");
        log.info("hash key save start");
        Map<String, String> dataMap = new HashMap<>();
        for (int i = 0; i < 10000; i++) {
            String is = String.valueOf(i);
            dataMap.put(is, is);
        }
        stringRedisTemplate.opsForHash().putAll("scan:hash", dataMap);
        log.info("hash key save end");
        TimeUnit.SECONDS.sleep(5);
        log.info("开始hash scan");
        ScanOptions scanOptions = ScanOptions.scanOptions()
                .count(3000)
                .build();
        Cursor<Map.Entry<Object, Object>> scan = stringRedisTemplate.opsForHash().scan("scan:hash", scanOptions);
        List<Map.Entry<Object, Object>> collect = scan.stream().collect(Collectors.toList());
        log.info("scan result: size:{}", collect.size());
        scan.close();
        stringRedisTemplate.delete("scan:hash");
        log.info("结束");
    }
}
